package by.averianov.discounta.webapp.page.create;

import javax.inject.Inject;

import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.Shop;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.BaseLayout;

public class CreateShop extends BaseLayout {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CreateShop.class);

	private Long id;
	private String nameShop;
	
	private PageCreator pageCreator;

	public CreateShop(Shop shop, PageCreator pageCreator) {
		super(null);
		this.pageCreator = pageCreator;
		
		try {
			this.id = shop.getId(); 
			this.nameShop = shop.getNameShop();
			LOGGER.debug("Shop is changing");
		} catch (Exception e) {
			LOGGER.debug("Shop is creating");
			//this.id = null;
		}
	}

	@Inject
	private UserService userService;


	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		final TextField<String> nameShopText = new TextField<String>("nameShop", Model.of(nameShop));
		
		Form<?> form = new Form<Void>("shopCreateForm") {
			@Override
			protected void onSubmit() {
				
				PageParameters pageParameters = new PageParameters();
				
				pageParameters.add("nameShop", nameShopText.getModelObject());
				StringValue nameShopValue = pageParameters.get("nameShop");
				
				
		        LOGGER.debug("Set Shop");
		        Shop shop = userService.createShop(id, nameShopValue.toString());
		        userService.saveOrUpdateShop(shop);
				setResponsePage(pageCreator.createPage());
			}
		};		 
		add(form);
		
		form.add(nameShopText);
		form.add(new Label("labelCreateShop", getLabelCreateShop(id)));
		form.add(new Label("labelShopIdText", getLabelShopId()));		
		final Label labelShopId = new Label("labelShopId", id);
		form.add(labelShopId);			
		form.add(new Label("labelNameShop", getLabelNameShop()));	
		form.add(new Label("labelSave", getButtonSave()));	
		
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
				
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
		
	}

}